package com.sporch.component;

import com.czy.annotation.RequiredPermission;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: czy
 * @Description: 权限验证拦截器
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (hasPermission(handler)){
            System.err.println("校验通过");
            return true;
        }
        System.err.println("校验失败");
        return false;
    }

    private boolean hasPermission(Object handler){
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod=(HandlerMethod) handler;
            // 获取方法上的注解
            RequiredPermission requiredPermission = handlerMethod.getMethodAnnotation(RequiredPermission.class);
            if (requiredPermission==null){
                // 如果方法上的注解为空 则获取类的注解
                requiredPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredPermission.class);
            }
            // 如果注解为null, 说明不需要拦截, 直接放过
            if (requiredPermission==null){
                return true;
            }
            // 如果标记了注解则判断权限
            if (StringUtils.isNotBlank(requiredPermission.value())){
                String value = requiredPermission.value();
                return value.equals("admin");
            }
        }
        return false;
    }
}
